<template>
    <div class="images_library">
        <!-- type="border-card" -->
        <el-tabs
            v-loading="selfLoading"
            v-model="activeName"
            tab-position="left"
            @tab-click="handleLeftClick"
            style="height:490px;"
            class="images_tabs"
        >
            <el-tab-pane
                v-for="type in typeLists"
                :label="type.name"
                :key="type.id"
                :name="type.id"
            >
                <level1Tabs
                    v-if="type.name != '我的上传'"
                    :typeList="type.children"
                    :list="imgsList"
                    :page="pageSet"
                    :loading="loading"
                    @selected="selectThisImg"
                    @handleClick="handleTabClick"
                    @close="close"
                    @pageChange="handlePageChange"
                ></level1Tabs>
                <level1TabsCustom
                    v-else
                    :typeList="type.children"
                    :list="imgsList"
                    :page="pageSet"
                    :loading="loading"
                    :isManage="isManage"
                    @selected="selectThisImg"
                    @handleClick="handleTabClick"
                    @close="close"
                    @pageChange="handlePageChange"
                    @delFolder="delFolder"
                ></level1TabsCustom>
            </el-tab-pane>
        </el-tabs>
         <!-- v-if="parentTab.name == '我的上传'" -->
        <div class="btn_group">
            <el-button class="uploadBtn" type="primary" @click="isManage = !isManage">{{ isManage ? '取消管理' : '管理' }}</el-button>
            <br />
            <el-button class="uploadBtn" type="primary" @click="openAddFolder">添加分类</el-button>
            <br />
            <el-button class="uploadBtn" type="primary" @click="openAddImg">上传图片</el-button>
        </div>

        <el-dialog
            title="上传图片"
            :visible.sync="isAddPic"
            width="300px"
            append-to-body
            @close="isAddPic = false">
            <el-upload
                class="upload-demo"
                ref="upload"
                :data="para"
                :headers="token"
                :action="actionUrl"
                :multiple="true"
                :limit="limitNum"
                :file-list="fileList"
                :on-success="handleSuccess"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                accept="image/*"
                :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
                <el-button
                    style="margin-left: 10px;"
                    size="small"
                    type="success"
                    @click="submitUpload"
                >上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">文件大小不超过5Mb</div>
            </el-upload>
            <span slot="footer">
                <!-- <el-button @click="isAddPic = false">取 消</el-button> -->
                <!-- <el-button type="primary" @click="addFolder">确 定</el-button> -->
            </span>
        </el-dialog>

        <el-dialog
          title="添加目录"
          :visible.sync="isAddMenu"
          width="400px"
          append-to-body>
          <el-input v-model.trim="addMenuInput" maxlength="4" placeholder="最多可输入四个字符"></el-input>
          <span slot="footer">
            <el-button @click="isAddMenu = false">取 消</el-button>
            <el-button type="primary" @click="addFolder">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
// 自定义事件 selected 接受一个参数，返回选中的图片数据信息，Object

import level1Tabs from './level1Tabs';
import level1TabsCustom from './level1TabsCustom';
export default {
    components: {
        level1Tabs,
        level1TabsCustom,
    },
    props: {
        pageSize: {
            type: Number,
            default: 15,
        },
    },
    created() {
        console.log('createdImgsLibrary');
        this.fetchImgTypes();
        // this.$bus.$on("delImgItem",this.delImgItem)
        this.$bus.$on("fetchList",this.fetchImgsList)
    },
    beforeDestroy(){
        // this.$bus.$off("delImgItem");
        // this.$bus.$off("fetchList");
    },
    data() {
        return {
            token: { 'x-auth-token': sessionStorage.getItem('token') },
            actionUrl: window.location.origin + '/dataft/upload/img',
            typeLists: [],
            menu: '',
            activeName: '',
            isAddPic: false,
            fileList: [],
            imgsList: [],
            limitNum: 6, //单次最大上传个数
            pageSet: {   // 分页配置信息
                pageIndex: 1,
                pageSize: this.pageSize,
                totalPage: 0,
            },
            parentTab: {}, // 左侧当前tab
            currentTab: { id: '0' }, // 二级tab
            para: { foldId: '' },   // 上传图片的额外参数 
            isAddMenu:false,
            addMenuInput:"",
            selfLoading:true,
            loading:false,
            isManage:false
        };
    },
    watch: {
        isAddPic(newValue, oldValue) {
            if (newValue) {
                this.para = {
                    foldId: this.currentTab.id,
                };
            }
        },
    },
    methods: {
        openAddImg(){
          this.isManage = false;
          this.isAddPic = true;
        },
        openAddFolder(){
          this.isManage = false;
          this.isAddMenu = true;
          this.addMenuInput = "";
        },
        // 本地删除单个图片
        delImgItem(item){
            var curDelIndex = this.imgsList.findIndex(img=>{
              return img.id === item.id
            })
            this.imgsList.splice(curDelIndex,1)
        },
        closeAddMenu(){},
        // 左侧tab切换时触发
        handleLeftClick(tab) {
            this.parentTab = this.typeLists.find(item => {
                return item.id === tab.name;
            });
            // 激活当前tab首个子tab
            if (
                this.parentTab.children &&
                this.parentTab.children.length === 0
            ) {
                this.currentTab = this.parentTab;
            } else {
                this.currentTab = this.parentTab.children[0];
            }
            this.fetchImgsList();
        },
        //  页码改变的时候触发
        handlePageChange(page) {
            this.pageSet.pageIndex = page;
            this.fetchImgsList();
        },

        handleTabClick(tab) {
            this.currentTab = this.parentTab.children.find(item => {
                return item.id === tab.name;
            });
            this.fetchImgsList();
        },
        //图片上传
        beforeUpload(file){
          const isLt5M = file.size / 1024 / 1024 < 5;
          if (!isLt5M) {
              this.$message.error('上传图片大小不能超过 5MB!');
              return false
          }
        },
        // 图片上传
        submitUpload() {
            this.$refs.upload.submit();
        },
        // 文件数量超出限定数
        handleExceed() {
            this.$message.warning(`单次最多上传${this.limitNum}张图片`);
        },
        handleSuccess(response) {
            if (response.msg === '操作成功') {
              console.log('object');
                this.$message.success('上传成功');
                this.isAddPic = false;
                // 如果当前页面的个数达到最大个数，删除最后一个
                if (this.typeLists.length == this.pageSet.pageSize) {
                    this.typeLists.pop();
                }
                this.imgsList.unshift(response.data[0]);
                // 清除图片列表后存在问题，暂时没有接解决方案
                // this.$refs.upload.clearFiles();
                this.fetchImgsList();
            }else{
                this.$message.error("上传失败")
            }
        },

        // 添加目录
        addFolder() {
            if(this.addMenuInput){
                if(this.parentTab.children.length > 6){
                   this.$message.warning("最多可以创建6个自定义分类！")
                    return
                }
                var isExist = this.parentTab.children.findIndex(item=>{
                  return item.name === this.addMenuInput
                })
                if(isExist != -1){
                    this.$message.warning("当前分类已存在！")
                    return
                }
                var para = {
                  parentId: this.parentTab.id, // 父类id
                  name: this.addMenuInput,
                  foldType: 1, // 0 是公共  1是个人库
                  folded: 0, // 区分类别  1目录 0 类别
                };
                this.$api.post('/folder/add', para, res => {
                    console.log('res :', res);
                    this.parentTab.children.push(res);
                    this.isAddMenu = false;
                });
            }else{
              this.$message.warning("请输入名称")
            }
        },
        delFolder(id){
          var folderArr = this.parentTab.children;
          var curDelIndex = folderArr.findIndex(folder=> folder.id === id)
          folderArr.splice(curDelIndex,1)
        },
        // 获取图片分类
        fetchImgTypes() {
            this.selfLoading = true;
            this.$api.get(
                '/folder/list',
                null,
                res => {
                    this.typeLists = res;
                    this.parentTab = this.typeLists[0];
                    this.currentTab = this.parentTab && this.parentTab.children[0] || {};
                    // 设置默认tab页
                    this.activeName = res && res[0] && res[0].id;
                    this.selfLoading = false;
                    this.fetchImgsList();
                },
                err => {
                    this.$message.error('未获取到图片分类');
                    this.selfLoading = false;
                }
            );
        },

        // 获取分页图片
        fetchImgsList(isLastImg) {
            //  删除最后一页的图片时，页码往前一页   imgList组件里的方法传递标识
            if(isLastImg && this.pageSet.pageIndex > 1){
              this.pageSet.pageIndex--;
            }
            this.loading = true;
            var para = {
                foldId: this.currentTab.id,
                index: this.pageSet.pageIndex || 1,
                pageSize: this.pageSet.pageSize || this.pageSize,
            };
            this.$api.post('/img/list', para, res => {
                this.loading = false;
                this.imgsList = res.result;
   
                this.pageSet.pageIndex = res.pageIndex;
                this.pageSet.pageSize = res.pageSize;
                this.pageSet.totalPage = res.totalPage;
            },err=>{
                this.loading = false;
                this.$message.error(err)
            });
        },
        // 选择图片
        selectThisImg(data) {
            this.$emit('selected', data);
        },
        close() {
            this.isManage = false;
            this.$emit('close');
        },
    },

};
</script>

<style lang="scss">
.images_library {
    position: relative;
    .btn_group {
        position: absolute;
        bottom: 10px;
        width: 96px;
        button {
            width: 100%;
            border-radius: 0;
            margin-top: 10px;
        }
    }
    .images_tabs {
        .el-tabs__header.is-left {
            margin-right: 20px;
        }
    }
    .el-tabs--left .el-tabs__item.is-left.is-active{
      background-color: #409EFF;
      color: #fff;
    }
}
</style>